class OrdersController < ApplicationController

  def autocomplete_order_info
    params[:key_word] = "%#{params[:term]}%"
    @orders = Order.where('buyer_full_name like :key_word or buyer_phone like :key_word or buyer_address like :key_word or order_no like :key_word',params)
  end
  
  def autocomplete_furniture_code
    params[:key_word] = "%#{params[:term]}%"
    @order_items = OrderItem.select('distinct (furniture_code + furniture_name) ,furniture_code,furniture_name').where('furniture_code like :key_word',params).order('created_at desc')
  end
  
  def autocomplete_furniture_name
    params[:key_word] = "%#{params[:term]}%"
    @order_items = OrderItem.select('distinct (furniture_code + furniture_name),furniture_code,furniture_name').where('furniture_name like :key_word',params).order('created_at desc')
  end

  def index
    if params[:filter].present?
      @orders = Order.try(params[:filter],params[:on]) || []
    else
      params[:status_request] ||= 'being_edited'
      @orders = Order.try(params[:status_request]) || []
    end
  end

  def xxed_on
    @graph = open_flash_chart_object(600,125,url_for(:action => "month_stat_chart_for_#{params[:filter]}", :filter => params[:filter] ,:on => params[:on]), true, "/", "open-flash-chart-bar-clicking.swf")
    @on = params[:on].nil? ? Date.today : Date.parse(params[:on])
    render :template => "orders/#{params[:filter]}.js"
  end

  # 月统计视图-交货数
  def month_stat_chart_for_delivered_on
    month_stat_chart_for_xxed_on :xx => '交货'
  end

  # 月统计视图-逾期交货数
  def month_stat_chart_for_overdue_delivered_on
    month_stat_chart_for_xxed_on :xx => '逾期交货'
  end

  # 月统计视图-上门安装数
  def month_stat_chart_for_installed_on
    month_stat_chart_for_xxed_on :xx => '上门安装'
  end

  # 月统计视图-售后服务数
  def month_stat_chart_for_after_serviced_on
    month_stat_chart_for_xxed_on :xx => '售后服务'
  end

  # 月统计视图-厂家订做数
  def month_stat_chart_for_order_made_on
    month_stat_chart_for_xxed_on :xx => '厂家订做'
  end

  # 月统计视图-支付订做数
  def month_stat_chart_for_payed_on
    month_stat_chart_for_xxed_on :xx => '支付订做'
  end

  # 月统计视图-入库登记数
  def month_stat_chart_for_entered_on
    month_stat_chart_for_xxed_on :xx => '入库登记'
  end

  # 月统计视图-预订数
  def month_stat_chart_for_ordered_on
    month_stat_chart_for_xxed_on :xx => '预订'
  end

  # 月统计视图-归档数
  def month_stat_chart_for_filed_on
    month_stat_chart_for_xxed_on :xx => '归档'
  end

  # 月统计视图-作废数
  def month_stat_chart_for_blanked_out_on
    month_stat_chart_for_xxed_on :xx => '作废'
  end

  def edit
    @order = Order.find(params[:id])
  end

  def update
    @order = Order.find(params[:id])
    error_message_follows_field_in_new_line
    render :edit if not @order.update_attributes params[:order]
  end

  def destroy
    @order_item = OrderItem.find(params[:id])
    @order_item.destroy
  end

  def show
    if params[:id] == 'from_autocomplete'
      redirect_to Order.find(params[:order_id])
    else
      @order = Order.find(params[:id])
    end
  end
  
  def create     
    @order = Order.new
    @order.init_order_no
    @order.save(:validate => false)
    redirect_to @order
  end

  def new_order_item
    @order_item = OrderItem.new(:order_id => params[:id])
  end

  def create_order_item
    @order_item = OrderItem.new(params[:order_item])    
    render :new_order_item if not @order_item.save
  end

  def edit_order_item
    @order_item = OrderItem.find(params[:id])    
  end

  def update_order_item
    @order_item = OrderItem.find(params[:id])    
    render :edit_order_item if not @order_item.update_attributes(params[:order_item])
  end

  def show_order_item
    show
  end

  def order_item_feeds
    @order_item = OrderItem.find(params[:id])
  end
  
  def new_order_made
    @order_made = OrderMade.new(:order_item_id => params[:id])
  end

  def create_order_made
    @order_made = OrderMade.new(params[:order_made])
    render :new_order_made if not @order_made.save
  end
  
  def edit_order_made
    @feed = Feed.find(params[:id])
  end

  def update_order_made
    @order_made = OrderMade.find(params[:id])
    render :edit_order_made if not @order_made.update_attributes(params[:order_made])
  end

  def destroy_order_made
    @feed = Feed.find(params[:id])
    # 如果删除的是厂家下单，则判断它是否有入库登记或订做付款项，如果有则不允许删除。
    if @feed.is_a?(Feed::OrderMadeCreated) and not @feed.order_made.can_destroy?
      @error_info = "请先删除相关的入库登记或订做付款项！"
    else
      @feed.destroy
    end
  end
  
  def new_enter
    @enter = Enter.new(:order_item_id => params[:id])
    @order_mades = OrderMade.where(:order_item_id => params[:id]).order('created_at desc')
  end

  def create_enter
    @enter = Enter.new(params[:enter])
    render :new_enter if not @enter.save
  end

  def edit_enter
    @feed = Feed.find(params[:id])
  end

  def update_enter
    @enter = Enter.find(params[:id])
    render :edit_enter if not @enter.update_attributes(params[:enter])
  end

  def destroy_enter
    @feed = Feed.find(params[:id])
    @feed.enter.destroy
  end

  def new_payment
    @order_made_payment = OrderMadePayment.new(:order_item_id => params[:id])    
    @order_mades = OrderMade.where(:order_item_id => params[:id]).has_been_sent_to_factory
  end

  def create_payment
    @order_made_payment = OrderMadePayment.new(params[:order_made_payment])
    render :new_payment if not @order_made_payment.save
  end

  def destroy_payment
    @feed = Feed.find(params[:id])
    @feed.order_made_payment.destroy
  end

  def edit_payment
    @feed = Feed.find(params[:id])
  end

  def update_payment
    @order_made_payment = OrderMadePayment.find(params[:id])
    render :edit_payment if not @order_made_payment.update_attributes(params[:order_made_payment])
  end


  def new_installation
    @installation = Installation.new(:order_item_id => params[:id])
  end

  def create_installation
    @installation = Installation.new(params[:installation])
    render :new_installation if not @installation.save
  end

  def edit_installation
    @feed = Feed.find(params[:id])
  end

  def update_installation
    @installation = Installation.find(params[:id])
    render :edit_installation if not @installation.update_attributes(params[:installation])
  end

  def destroy_installation
    @feed = Feed.find(params[:id])
    # 如果删除的是派工安装，则判断它是否有售后服务或安装完成项，如果有则不允许删除。
    if @feed.is_a?(Feed::InstallCreated) and not @feed.installation.can_destroy?
      @error_info = "请先删除相关的安装完成或未完成项！"
    else
      @feed.destroy
    end
  end
  
  def new_installed
    @installation = Installation.new(:order_item_id => params[:id])
    @installations = Installation.where(:order_item_id => params[:id]).has_been_sent_to_installer
  end

  # 安装完成
  def create_installed
    @installation = Installation.find(params[:installation][:id])
    if not @installation.update_attributes(params[:installation])
      render :new_installed
    else
      @installation.installed!
    end
    @installation.reload
  end

  def edit_installed
    @feed = Feed.find(params[:id])
  end

  def update_installed
    @installation = Installation.find(params[:id])
    render :edit_installed if not @installation.update_attributes(params[:installation])
    @installation.reload
  end

  def new_install_unfinished
    @installation = Installation.new(:order_item_id => params[:id])
    @installations = Installation.where(:order_item_id => params[:id]).has_been_sent_to_installer
  end

  def create_install_unfinished
    @installation = Installation.find(params[:installation][:id])
    if not @installation.update_attributes(params[:installation])
      render :new_install_unfinished
    else
      @installation.install_unfinished!
    end
    @installation.reload
  end

  def edit_install_unfinished
    @feed = Feed.find(params[:id])
  end

  def update_install_unfinished
    @installation = Installation.find(params[:id])
    render :edit_install_unfinished if not @installation.update_attributes(params[:installation])
    @installation.reload
  end
  
  def new_after_serviced
    @after_service = AfterService.new(:order_item_id => params[:id])
  end

  def create_after_serviced
    @after_service = AfterService.new(params[:after_service])
    render :new_after_serviced if not @after_service.save
  end
  
  def edit_after_serviced
    @feed = Feed.find(params[:id])
  end

  def update_after_serviced
    @after_service = AfterService.find(params[:id])
    render :edit_after_serviced if not @after_service.update_attributes(params[:after_service])
    @after_service.reload
  end

  def destroy_after_service
    @feed = Feed.find(params[:id])
    # 如果删除的是售后服务，则判断它是否有完成或未完成项，如果有则不允许删除。
    if @feed.is_a?(Feed::AfterServiceCreated) and not @feed.after_service.can_destroy?
      @error_info = "请先删除相关的售后完成或未完成项！"
    else
      @feed.destroy
    end
  end

  def new_after_service_finished
    @after_service = AfterService.new(:order_item_id => params[:id])
    @after_services = AfterService.where(:order_item_id => params[:id]).has_been_sent_to_after_service
  end

  def create_after_service_finished
    @after_service = AfterService.find(params[:after_service][:id])
    if not @after_service.update_attributes(params[:after_service])
      render :new_after_service_finished
    else
      @after_service.finished!
    end
    @after_service.reload
  end

  def edit_after_service_finished
    @feed = Feed.find(params[:id])
  end

  def update_after_service_finished
    @after_service = AfterService.find(params[:id])
    render :edit_after_service_finished if not @after_service.update_attributes(params[:after_service])
    @after_service.reload
  end

  def new_after_service_unfinished
    @after_service = AfterService.new(:order_item_id => params[:id])
    @after_services = AfterService.where(:order_item_id => params[:id]).has_been_sent_to_after_service
  end

  def create_after_service_unfinished
    @after_service = AfterService.find(params[:after_service][:id])
    if not @after_service.update_attributes(params[:after_service])
      render :new_after_service_unfinished
    else
      @after_service.unfinished!
    end
    @after_service.reload
  end

  def edit_after_service_unfinished
    @feed = Feed.find(params[:id])
  end

  def update_after_service_unfinished
    @after_service = AfterService.find(params[:id])
    render :new_after_service_unfinished if not @after_service.update_attributes(params[:after_service])
    @after_service.reload
  end

  def new_completed
    @order_item = OrderItem.find(params[:id])
  end

  def create_completed
    @order_item = OrderItem.find(params[:id])
    if not @order_item.update_attributes(params[:order_item])
      render :new_completed
    else
      @order_item.completed!
    end
  end

  def edit_completed
    @order_item = OrderItem.find(params[:id])
  end

  def update_completed
    @order_item = OrderItem.find(params[:id])
    if not @order_item.update_attributes(params[:order_item])
      render :edit_completed
    end
  end

  def destroy_completed
    @feed = Feed.find(params[:id])
    @feed.destroy
  end

  def new_feed
    @order_item = OrderItem.find(params[:id])
  end
  
  def show_feed
    @feed_id = params[:id]
  end

  def edit_finance
    edit
  end

  def update_finance
    @order = Order.find(params[:id])
    error_message_follows_field_in_new_line
    render :edit_finance if not @order.update_attributes params[:order]
  end

  def show_finance
    show
  end
  
  def edit_buyer
    edit
  end

  def update_buyer
    @order = Order.find(params[:id])
    error_message_follows_field_in_new_line
    render :edit_buyer if not @order.update_attributes params[:order]
  end

  def show_buyer
    show
  end

  def edit_remark
    @order = Order.find(params[:id])
  end

  def update_remark
    @order = Order.find(params[:id])
    render :edit_remark if not @order.update_attributes params[:order]
  end

  def show_remark
    show
  end

  def effected
    @order = Order.find(params[:id])
    try_update_stauts(:effected!)
    redirect_to @order
  end

  def being_edited
    @order = Order.find(params[:id])
    try_update_stauts(:being_edited!)
    redirect_to @order
  end

  def filed
    @order = Order.find(params[:id])
    try_update_stauts(:filed!)
    redirect_to @order
  end

  def blanked_out
    @order = Order.find(params[:id])
    try_update_stauts(:blanked_out!)
    redirect_to @order
  end

  def show_status
    @order = Order.find(params[:id])
  end
  
  def sales_contract
    @order = Order.find(params[:id])
    render :layout => false
  end

  def help_for_first_order_step_1
    
  end

  def help_for_first_order_step_2_3_4_5_6
    @order = Order.find(params[:id])
  end

  def reset_feeds_position
    params[:feed].each_with_index do |id, index|
      Feed.find(id).position!(index)
    end
  end

  def tasks
    @feed = Feed.find(params[:feed_id])
  end
  
  def new_task
    feed = Feed.find(params[:id])
    @task = Task.new(
      :feed_id => feed.id,
      :order_item => feed.order_item,
      :executor_id => User.current
    )
  end

  def create_task
    @task = Task.new(params[:task])
    render :new_task if not @task.save
  end

  def edit_task
    @task = Task.find(params[:id])
  end

  def update_task
    @task = Task.find(params[:id])
    render :edit_task if not @task.update_attributes(params[:task])
  end

  def destroy_task
    @task = Task.find(params[:id])
    @task.destroy
  end
  
  private
  def try_update_stauts(request)
    if @order.being_edited_by_other_user? # 是否其他用户正在编辑？
      flash[:notice] = "【#{@order.being_edited_by_user.full_name}】正在编辑该订单，请稍候..."
    else
      @order.try(request)
    end
  end

  def month_stat_chart_for_xxed_on(args = {})
    on = params[:on].present? ? Date.parse(params[:on]) : Date.today
    bar = BarGlass.new
    bar.set_colour('#56BD35')
    params[:max_count] ||= 0
    bar.set_values(
      (1..12).each_with_object([]) do |month, values|
        value = Order.try("#{params[:filter]}_month",on.year,month).count
        params[:max_count] = params[:max_count] < value ? value : params[:max_count]
        values << BarValue.new(value);
        values.last.set_tooltip("<b>#{month}月</b><br>#{value}单");
        values.last.on_click = "select_month(#{on.year},#{month})";
      end
    )

    x_axis = XAxis.new
    x_axis.set_labels(["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"])

    y_axis = YAxis.new
    y_axis.set_range(0, params[:max_count] * 1.1  + 1, (params[:max_count] * 1.1 / 5).to_i)

    chart = OpenFlashChart.new
    chart.set_x_axis(x_axis)
    chart.set_y_axis(y_axis)
    chart.set_bg_colour('#ffffff')
    chart.set_title(Title.new("#{on.year}年#{args[:xx]}的预订单数月统计"))
    chart.add_element(bar)
    render :text => chart,:layout => false
  end

  def update_visible
    @order = Order.find(params[:id])
    if params[:order][:visible_scope] == "everyone" || params[:order][:visible_scope] == "myself"
      @order.update_attributes(params[:order])
    else
      if params[:order][:visible_scope] == "groups"
         params[:order][:visible_order_to_groups] ||= []
         params[:group_ids].each do |group_id|
           visible_order_to_group = VisibleOrderToGroup.new(:enterprise_id => @order.enterprise_id, :order_id => @order.id, :group_id => group_id)
           params[:order][:visible_order_to_groups] << visible_order_to_group
         end
         @order.update_attributes(params[:order])
      end
      if params[:order][:visible_scope] == "users"
         params[:order][:visible_order_to_users] ||= []
         params[:user_ids].each do |user_id|
           visible_order_to_user = VisibleOrderToUser.new(:enterprise_id => @order.enterprise_id, :order_id => @order.id, :user_id => user_id)
           params[:order][:visible_order_to_users] << visible_order_to_user
         end
         @order.update_attributes(params[:order])
      end
    end
  end

  def close_can_see
    @order  = Order.find(params[:id])
  end
end
